using System;
using System.Collections.Generic;
using System.Reflection;

namespace XTengine.ComponentModel
{
    public class XTengineComponentBase
    {
        public XTengineObject Site { get; set; }

        public void SetProperty(Type componentType, string name, string value)
        {
            if (!componentType.IsInterface)
                return;

            Dictionary<string, PropertyInfo> componentProperties;
            bool foundMap = ComponentManager.ComponentPropertyMap.TryGetValue(componentType, out componentProperties);

            if (!foundMap)
                return;

            PropertyInfo propertyToSet;
            bool foundProperty = componentProperties.TryGetValue(name.ToLower(), out propertyToSet);

            if (!foundProperty)
                return;

            IXTengineComponent thisInterface = this.Site.GetComponent(componentType);
            propertyToSet.SetValue(thisInterface, TypeConverters.Convert(propertyToSet.PropertyType, value), null);
        }

        public void SetProperty<T>(string name, object value) where T : IXTengineComponent
        {
            Type interfaceType = typeof(T);

            Dictionary<string, PropertyInfo> componentProperties;
            bool foundMap = ComponentManager.ComponentPropertyMap.TryGetValue(interfaceType, out componentProperties);

            if (!foundMap)
                return;

            PropertyInfo propertyToSet;
            bool foundProperty = componentProperties.TryGetValue(name, out propertyToSet);

            if (!foundProperty)
                return;

            T thisInterface = (T)this.Site.GetComponent<T>();

            propertyToSet.SetValue(thisInterface, value, null);
        }
    }
}
